new Vue({
  el: '#mainBody',
  data: function () {
    return {
      dialogVisible: false, //数据上传dialog
      addDataTypeVisible: false, //创建数据类型dialog
      searchForm: { //查询条件
        select: '',
        month: ''
      },
      currentpage:1,//当前页数
      pageBean:[//分页参数列表
      ],
      dataTypes: [ //数据类型
      ],
      dataTypesList: [ //数据类型列表
      ],
      ruleForm: { //form v-model
        name: '',
        files:''
      },
      rules: { //from 验证
        name: [
          { required: true, message:'请输入数据类型', trigger: 'blur'}
        ]
      }
    };
  },
  created: function () {
	 //页面加载查询数据类型
     this.findDataTypesByPage(1);//第一页数据
     this.findAllDataTypes();
  },
  methods: {
	/**下一页 上一页按钮 */
  	handleCurrentChange:function(val){
  		this.currentpage=val;
		this.findDataTypesByPage(val,'handleCurrentChange');
  	},
	resetSearchForm: function (formName) {
  		this.$refs[formName].resetFields()
  		this.currentpage = 1;
  		this.findDataTypesByPage(1);//第一页数据
  	},
  	downloadTemplate: function(id){
  		window.location.href='/datatype/downloadTemplate?id='+id;
  	},
	operateDataType:function (dataTypesItem,state) {
		_this = this;
		if(dataTypesItem.state == state){
			if(state==1) successMessage(_this.$message, "已启用");
			if(state==0) successMessage(_this.$message, "已禁用");	
			return;
		}
		
		$.ajax({
            url: '/datatype/operateDataType',
            data:{"id":dataTypesItem.id,"state":state},
            type: 'post',
            dataType: 'json',
            success: function (res) {
            	if (res.data.status=='1') {
          		  errorMessage(_this.$message, res.data.msg);
          	  } else {
          		  dataTypesItem.state=state;
          		  successMessage(_this.$message, res.data.msg);
          		  console.info(res.data.msg);
          	  }
            },
            error: function (err) {
                if(err.responseJSON.message=="session clean"){
                    errorMessage(_this.$message, '登陆已失效重新登陆!');
                    toLogin();
                    return;
                }
                if(err.status == 403){
                    errorMessage(_this.$message, "没有权限，请先申请该权限！");
                    return;
                }
                errorMessage(_this.$message,err);
            }
        })
	},
	remove: function (id,index) {
		var _this = this;

        this.$confirm('确认要删除?删除后不可恢复', '删除提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(function () {
            $.ajax({
                url: '/datatype/removeDataType',
                data:{"data":id},
                type: 'post',
                dataType: 'json',
                success: function (res) {
                    if (res.data.status=='1') {
                        errorMessage(_this.$message, res.data.msg);
                    } else {
                        successMessage(_this.$message, res.data.msg);
                        _this.dataTypes.splice(index,1);

                        _this.findDataTypesByPage(1);
                    }
                    console.info(res.data.msg);
                },
                error: function (err) {
                    if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    if(err.status == 403){
                        errorMessage(_this.$message, "没有权限，请先申请该权限！");
                        return;
                    }
                    errorMessage(_this.$message,err);
                }
            })
        }).catch(function () {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });
        });
	},
	createDaTypeShow: function () {
      this.dialogVisible = true
    },
    closeDialog: function(formName){
      this.$refs[formName].resetFields()
      var file = document.getElementById('file')
      file.value=''
      file.outerHTML = file.outerHTML
  	},
    findAllDataTypes: function() {
    	_this = this;
    	$.ajax({
            url: '/datatype/findAllDataTypes',
            type: 'post',
            dataType: 'json',
            success: function (res) {
	           	_this.dataTypes = res.data;
            },
            error: function (err) {
            	if(err.responseJSON.message=="session clean"){
                    errorMessage(_this.$message, '登陆已失效重新登陆!');
                    toLogin();
                    return;
                }
                errorMessage(_this.$message,err);
            }
        })
    },
    findDataTypesByPage: function (page,handelEvent){
    	var _this = this;
    	if(handelEvent!='handleCurrentChange') this.currentpage = 1;//初始化到第一页
    	var data = {"select":_this.searchForm.select,"month":formatDateYYYYMMDD(_this.searchForm.month),"currentPage":page};
    	console.info(JSON.stringify(data));
    	$.ajax({
             url: '/datatype/findDataTypesByPage',
             data:{"data":JSON.stringify(data)},
             type: 'post',
             dataType: 'json',
             success: function (res) {
            	_this.exhibition(res);
             },
             error: function (err) {
                 if(err.responseJSON.message=="session clean"){
                     errorMessage(_this.$message, '登陆已失效重新登陆!');
                     toLogin();
                     return;
                 }
                 if(err.status == 403){
                     errorMessage(_this.$message, "没有权限，请先申请该权限！");
                     return;
                 }
                 errorMessage(_this.$message,err);
             }
         })
    },
    /**
     * 
     * 处理页面数据展示
     * */
    exhibition: function(res){
    	var _this = this;
    	var datatype_arr=[];
    	res.data.beanList.forEach(function (obj) {
            var datatype = {}
            datatype['id']=obj.id
            datatype['code_NAME']=obj.codeName
            datatype['tucname']=obj.tucname
            datatype['create_TIME']= obj.createTime
            datatype['state']=obj.state
            datatype['templet_PATH']=obj.templetPath
            datatype_arr.push(datatype);
        })
        _this.dataTypesList = datatype_arr;
        var page = {}
        page['totalNumber'] = res.data.totalNumber
        page['totalPage'] = res.data.totalPage
        _this.pageBean = page
    },
    saveForm: function (formName){
      var _this = this
      this.$refs[formName].validate(function (valid) {
        if (valid) {
        	if($('#file')[0].files[0].size/1024/1024 > 10){
				errorMessage(_this.$message, "允许最大上传文件大小为10M");
				return;
			}
        	
            $.ajax({
              url: '/datatype/addDataType',
              type: 'post',
              data:{"data":JSON.stringify(_this.ruleForm)},
              dataType: 'json',
              async:false,
              success: function (res) {
            	  if (res.data.status=='1') {
            		  errorMessage(_this.$message, res.data.msg);
            	  } else {
            		  	var type = {}
						type['code_NAME'] = _this.ruleForm.name
						_this.dataTypes.unshift(type);
            		  	
						//上传模板
            		  	var tucname = res.data.tucname;
						var formData = new FormData();
						formData.append('file', $('#file')[0].files[0]);
						formData.append('file_name', _this.ruleForm.name);
						formData.append('id',res.data.id);
						if ($('#file')[0].files[0] == undefined || $('#file')[0].files[0] == null) {
							console.info('不上传模板');
						} else {
							console.info('上传模板');
							$.ajax({
							    url: '/datatype/uploadFile',
							    type: 'POST',
							    cache: false,
							    async:false, 
							    data: formData,
							    processData: false,
							    async:false,
							    contentType: false
							}).done(function(res) {
                                if (res.data.status=='1') {
                                    errorMessage(_this.$message, res.data.msg);
                                    return;
                                }
                                if (res.data.status=='0') {
                                    successMessage(_this.$message, res.data.msg);
                                    _this.dialogVisible = false;
            						_this.findDataTypesByPage(1);
                                    return;
                                }
							}).fail(function(res) {
								errorMessage(_this.$message, res);
							});
						}
						
						
            	  }
              },
              error: function (err) {
                  if(err.responseJSON.message=="session clean"){
                      errorMessage(_this.$message, '登陆已失效重新登陆!');
                      toLogin();
                      return;
                  }
                  if(err.status == 403){
                      errorMessage(_this.$message, "没有权限，请先申请该权限！");
                      return;
                  }
                  errorMessage(_this.$message,err);
              }
          })
        } else {
          return false
        }
      })
    }
  }
})
function fomatterDate(date) {
  var $year = date.getFullYear()
  var $month = date.getMonth() + 1
  var $date = date.getDate()
  return $year + '-' + $month + '-' + $date
}

